/*
 * Copyright (C) 2017-2021
 * All rights reserved, Designed By
 * Copyright authorization contact 18814114118
 */
package com.shop.cereshop.business.service.shop.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.shop.cereshop.business.param.shop.ShopQualificationParam;
import com.shop.cereshop.business.service.shop.CereShopQualificationFlowService;
import com.shop.cereshop.commons.constant.CoReturnFormat;
import com.shop.cereshop.commons.constant.IntegerEnum;
import com.shop.cereshop.commons.domain.business.CerePlatformBusiness;
import com.shop.cereshop.commons.domain.im.tx.resp.ocr.BizLicenseOCRResp;
import com.shop.cereshop.commons.domain.shop.CereShopQualificationFlow;
import com.shop.cereshop.commons.domain.user.faceCheck.respond.AliFaceCheckRespond;
import com.shop.cereshop.commons.domain.user.faceCheck.respond.FaceCheckRespond;
import com.shop.cereshop.commons.exception.CoBusinessException;
import com.shop.cereshop.commons.service.ocr.TencentOCRService;
import com.shop.cereshop.commons.utils.EmptyUtils;
import com.shop.cereshop.commons.utils.HttpUtils;
import com.shop.cereshop.commons.utils.TimeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;

/**
 * 店铺资质认证流程管理服务实现类
 */
@Slf4j
@Service
public class CereShopQualificationFlowServiceImpl implements CereShopQualificationFlowService {

    @Autowired
    private TencentOCRService tencentOCRService;

    // 这里需要注入对应的DAO和Service
    // @Autowired
    // private CereShopQualificationFlowDAO cereShopQualificationFlowDAO;
    // @Autowired
    // private CerePlatformShopService cerePlatformShopService;
    // @Autowired
    // private CereBusinessShopService cereBusinessShopService;
    // @Autowired
    // private FaceRecognitionService faceRecognitionService; // 人脸识别服务
    @Value("${ali.facecheck.appcode}")
    String appcode;
    @Value("${ali.facecheck.host}")
    String host;
    @Value("${ali.facecheck.path}")
    String path;
    @Override
    @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = {CoBusinessException.class, Exception.class})
    public String startQualificationFlow(ShopQualificationParam param, CerePlatformBusiness user) throws CoBusinessException {
        String time = TimeUtils.yyMMddHHmmss();
        String flowId = IdUtil.simpleUUID();

        try {
            // 1. 创建认证流程记录
            CereShopQualificationFlow flow = new CereShopQualificationFlow();
            flow.setFlowId(flowId);
            flow.setBusinessUserId(user.getBusinessUserId());
            flow.setShopType(param.getShopType());
            flow.setFlowStatus(1); // 进行中
            flow.setBusinessLicenseUrl(param.getBusinessLicenseUrl());
            flow.setIndustryLicenseUrl(param.getIndustryLicenseUrl());
            flow.setIdCardFrontUrl(param.getIdCardFrontUrl());
            flow.setIdCardBackUrl(param.getIdCardBackUrl());
            flow.setBrandAuthorizationUrl(param.getBrandAuthorizationUrl());
            flow.setTrademarkCertificateUrl(param.getTrademarkCertificateUrl());
            flow.setBusinessAddress(param.getBusinessAddress());
            flow.setApplicantName(param.getApplicantName());
            flow.setIdCardNumber(param.getIdCardNumber());
            flow.setPhoneNumber(param.getPhoneNumber());
            flow.setCompanyName(param.getCompanyName());
            flow.setSocialCreditCode(param.getSocialCreditCode());
            flow.setBrandName(param.getBrandName());
            flow.setMerchantName(param.getMerchantName());
            flow.setCreateTime(time);
            flow.setUpdateTime(time);

            // 2. 保存认证流程记录
            // cereShopQualificationFlowDAO.insert(flow);

            // 3. 如果启用OCR，自动进行营业执照识别
            if (param.getUseOCR() != null && param.getUseOCR()) {
                try {
                    Object ocrResult = recognizeBusinessLicense(param.getBusinessLicenseUrl(), flowId);
                    flow.setOcrResult(ocrResult.toString());
                    flow.setFlowStatus(2); // OCR完成
                    flow.setUpdateTime(TimeUtils.yyMMddHHmmss());
                    // cereShopQualificationFlowDAO.updateByPrimaryKeySelective(flow);
                } catch (Exception e) {
                    log.warn("OCR识别失败，但流程继续: {}", e.getMessage());
                }
            }

            return flowId;
        } catch (Exception e) {
            log.error("开始资质认证流程失败: {}", e.getMessage(), e);
            throw new CoBusinessException(CoReturnFormat.SYS_ERROR);
        }
    }

    @Override
    public Object recognizeBusinessLicense(String imageUrl, String flowId) throws CoBusinessException {
        try {
            // 1. 查询认证流程
            // CereShopQualificationFlow flow = cereShopQualificationFlowDAO.selectByPrimaryKey(flowId);
            // if (flow == null) {
            //     throw new CoBusinessException(CoReturnFormat.QUALIFICATION_FLOW_NOT_EXIST);
            // }

            // 2. 使用腾讯OCR识别营业执照
            BizLicenseOCRResp ocrResult = tencentOCRService.bizLicenseOCRByUrl(imageUrl);

            if (ocrResult == null || EmptyUtils.isEmpty(ocrResult.getRequestId())) {
                throw new CoBusinessException(CoReturnFormat.OCR_RECOGNITION_FAILED);
            }

            // 3. 构建返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("companyName", ocrResult.getName());
            result.put("socialCreditCode", ocrResult.getRegNum());
            result.put("legalPerson", ocrResult.getPerson());
            result.put("registeredCapital", ocrResult.getCapital());
            result.put("businessScope", ocrResult.getBusiness());
            result.put("address", ocrResult.getAddress());
            result.put("establishmentDate", ocrResult.getSetDate());
            result.put("validPeriod", ocrResult.getPeriod());
            result.put("registrationAuthority", ocrResult.getRegistrationAuthority());
            result.put("registrationDate", ocrResult.getRegistrationDate());

            // 4. 更新认证流程状态
            // flow.setOcrResult(result.toString());
            // flow.setFlowStatus(2); // OCR完成
            // flow.setUpdateTime(TimeUtils.yyMMddHHmmss());
            // cereShopQualificationFlowDAO.updateByPrimaryKeySelective(flow);

            return result;
        } catch (Exception e) {
            log.error("OCR识别营业执照失败: {}", e.getMessage(), e);
            throw new CoBusinessException(CoReturnFormat.OCR_RECOGNITION_FAILED);
        }
    }

    @Override
    @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = {CoBusinessException.class, Exception.class})
    public Object submitFaceRecognition(String name ,String idCardNumber, String faceImageUrl, String flowId) throws CoBusinessException {
        try {
            // 1. 查询认证流程
            // CereShopQualificationFlow flow = cereShopQualificationFlowDAO.selectByPrimaryKey(flowId);
            // if (flow == null) {
            //     throw new CoBusinessException(CoReturnFormat.QUALIFICATION_FLOW_NOT_EXIST);
            // }

            // 2. 调用人脸识别服务（这里需要调用app服务的人脸识别功能）
            // 可以通过HTTP调用或者消息队列调用app服务的人脸识别接口
            Map<String, Object> faceResult = callFaceRecognitionService(name,idCardNumber, faceImageUrl);

            // 3. 更新认证流程状态
            // flow.setFaceImageUrl(faceImageUrl);
            // flow.setFaceRecognitionResult(faceResult.toString());
            // flow.setFlowStatus(3); // 人脸识别完成
            // flow.setUpdateTime(TimeUtils.yyMMddHHmmss());
            // cereShopQualificationFlowDAO.updateByPrimaryKeySelective(flow);

            return faceResult;
        } catch (Exception e) {
            log.error("人脸识别失败: {}", e.getMessage(), e);
            throw new CoBusinessException(CoReturnFormat.FACE_RECOGNITION_FAILED);
        }
    }

    @Override
    @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = {CoBusinessException.class, Exception.class})
    public Object completeQualificationAndCreateShop(String flowId, CerePlatformBusiness user) throws CoBusinessException {
        String time = TimeUtils.yyMMddHHmmss();

        try {
            // 1. 查询认证流程
            // CereShopQualificationFlow flow = cereShopQualificationFlowDAO.selectByPrimaryKey(flowId);
            // if (flow == null) {
            //     throw new CoBusinessException(CoReturnFormat.QUALIFICATION_FLOW_NOT_EXIST);
            // }

            // 2. 验证流程状态
            // if (flow.getFlowStatus() < 3) {
            //     throw new CoBusinessException(CoReturnFormat.QUALIFICATION_NOT_COMPLETE);
            // }

            // 3. 创建店铺
            // CerePlatformShop shop = createShopFromFlow(flow);
            // Long shopId = cerePlatformShopService.createShop(shop);

            // 4. 创建商家用户与店铺关联关系
            // CereBusinessShop businessShop = new CereBusinessShop();
            // businessShop.setBusinessUserId(user.getBusinessUserId());
            // businessShop.setShopId(shopId);
            // businessShop.setIfBinding(IntegerEnum.YES.getCode());
            // cereBusinessShopService.insert(businessShop);

            // 5. 保存认证信息到对应的认证表
            // saveQualificationInfo(flow, shopId);

            // 6. 更新认证流程状态
            // flow.setFlowStatus(4); // 认证完成
            // flow.setCompleteTime(time);
            // flow.setUpdateTime(time);
            // cereShopQualificationFlowDAO.updateByPrimaryKeySelective(flow);

            // 7. 返回店铺信息
            Map<String, Object> result = new HashMap<>();
            // result.put("shopId", shopId);
            // result.put("shopName", shop.getShopName());
            result.put("message", "店铺创建成功，等待平台审核");

            return result;
        } catch (Exception e) {
            log.error("完成资质认证并创建店铺失败: {}", e.getMessage(), e);
            throw new CoBusinessException(CoReturnFormat.SYS_ERROR);
        }
    }

    @Override
    public Object getQualificationFlowStatus(String flowId) throws CoBusinessException {
        try {
            // 查询认证流程状态
            // CereShopQualificationFlow flow = cereShopQualificationFlowDAO.selectByPrimaryKey(flowId);
            // if (flow == null) {
            //     throw new CoBusinessException(CoReturnFormat.QUALIFICATION_FLOW_NOT_EXIST);
            // }

            Map<String, Object> result = new HashMap<>();
            // result.put("flowId", flow.getFlowId());
            // result.put("flowStatus", flow.getFlowStatus());
            // result.put("shopType", flow.getShopType());
            // result.put("createTime", flow.getCreateTime());
            // result.put("updateTime", flow.getUpdateTime());
            // result.put("completeTime", flow.getCompleteTime());
            // result.put("errorMessage", flow.getErrorMessage());

            return result;
        } catch (Exception e) {
            log.error("获取认证流程状态失败: {}", e.getMessage(), e);
            throw new CoBusinessException(CoReturnFormat.SYS_ERROR);
        }
    }

    @Override
    @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = {CoBusinessException.class, Exception.class})
    public String cancelQualificationFlow(String flowId, CerePlatformBusiness user) throws CoBusinessException {
        String time = TimeUtils.yyMMddHHmmss();

        try {
            // 1. 查询认证流程
            // CereShopQualificationFlow flow = cereShopQualificationFlowDAO.selectByPrimaryKey(flowId);
            // if (flow == null) {
            //     throw new CoBusinessException(CoReturnFormat.QUALIFICATION_FLOW_NOT_EXIST);
            // }

            // 2. 验证权限
            // if (!flow.getBusinessUserId().equals(user.getBusinessUserId())) {
            //     throw new CoBusinessException(CoReturnFormat.NO_PERMISSION);
            // }

            // 3. 更新流程状态
            // flow.setFlowStatus(5); // 已取消
            // flow.setUpdateTime(time);
            // cereShopQualificationFlowDAO.updateByPrimaryKeySelective(flow);

            return "认证流程已取消";
        } catch (Exception e) {
            log.error("取消认证流程失败: {}", e.getMessage(), e);
            throw new CoBusinessException(CoReturnFormat.SYS_ERROR);
        }
    }

    /**
     * 调用人脸识别服务
     */
    private Map<String, Object> callFaceRecognitionService(String name,String idCardNumber, String faceImageUrl) throws CoBusinessException {

        // 临时返回模拟结果
        Map<String, Object> result = new HashMap<>();



        // 这里需要调用app服务的人脸识别接口
        // 可以通过HTTP调用、消息队列或者直接调用app服务的服务类

        // 示例：HTTP调用
        // String url = "http://app-service/api/face/recognize";
        // Map<String, Object> params = new HashMap<>();
        // params.put("idCardNumber", idCardNumber);
        // params.put("faceImageUrl", faceImageUrl);
        //
        // // 发送HTTP请求
        // // ... HTTP调用逻辑

        String method = "POST";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        Map<String, String> querys = new HashMap<String, String>();
        Map<String, String> bodys = new HashMap<String, String>();
        bodys.put("name", name);
        bodys.put("id", idCardNumber);

       /* bodys.put("image_url", "确认可下载的服务器图片地址（image_url与image二选一）");
        bodys.put("image", "人脸图片的base64编码（image_url与image二选一）;*/
       bodys.put("image_url", faceImageUrl);
        try {
            /**
             * 重要提示如下:
             * HttpUtils请从\r\n\t    \t* https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java\r\n\t    \t* 下载
             *
             * 相应的依赖请参照
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
             */
            HttpResponse response = HttpUtils.doPost1(host, path, method, headers, querys, bodys);
            if (response.getStatusLine().getStatusCode() == 200) {
                //判断response.getEntity() 是否成功
                if (response.getEntity() != null) {
                    String entity = EntityUtils.toString(response.getEntity());
                    AliFaceCheckRespond bean = JSONUtil.toBean(entity, AliFaceCheckRespond.class);
                    if (bean.getStatus().equals("OK")) {
                        /*return FaceCheckRespond.builder().success(true)
                                .reqParam(JSONUtil.toJsonStr(bodys))
                                .name(name)
                                .idCardNumber(idCardNumber)
                                .reqResp(entity)
                                .build();*/
                        result.put("success", true);
                        result.put("similarity", 0.95);
                        result.put("message", "人脸识别成功");
                        return result;
                    } else {
                        /*return FaceCheckRespond.builder()
                                .success(false)
                                .reqParam(JSONUtil.toJsonStr(bodys))
                                .name(model.getName())
                                .idCardNumber(model.getIdCardNumber())
                                .reqResp(entity)
                                .build();*/
                        result.put("success", false);
                        result.put("similarity", 0.95);
                        result.put("message", "人脸识别失败");
                        return result;
                    }
                }
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("similarity", 0.95);
            result.put("message", "人脸识别失败");
            return result;

        }
        result.put("success", false);
        result.put("similarity", 0.95);
        result.put("message", "人脸识别失败");
        return result;





    }

    /**
     * 根据认证流程创建店铺
     */
    // private CerePlatformShop createShopFromFlow(CereShopQualificationFlow flow) {
    //     CerePlatformShop shop = new CerePlatformShop();
    //     shop.setShopName(flow.getCompanyName() != null ? flow.getCompanyName() : flow.getMerchantName());
    //     shop.setAuthenType(flow.getShopType());
    //     shop.setAuthenticationState(2); // 认证中
    //     shop.setCheckState(0); // 未处理
    //     shop.setState(IntegerEnum.YES.getCode());
    //     shop.setCreateTime(TimeUtils.yyMMddHHmmss());
    //     shop.setUpdateTime(TimeUtils.yyMMddHHmmss());
    //     return shop;
    // }

    /**
     * 保存认证信息到对应的认证表
     */
    // private void saveQualificationInfo(CereShopQualificationFlow flow, Long shopId) {
    //     switch (flow.getShopType()) {
    //         case 1: // 普通企业店
    //             saveEnterpriseInfo(flow, shopId);
    //             break;
    //         case 2: // 个体工商户
    //             saveIndividualBusinessInfo(flow, shopId);
    //             break;
    //         case 3: // 品牌旗舰店
    //             saveBrandInfo(flow, shopId);
    //             break;
    //     }
    // }
}
